%This file generates a case of a 20x20 Cov-matrix with up to 10 sub blocks.
%10 sampled sequences of same length are generated for use in the
%expected value objective function.
%The performance is measured for different number of blocks and different
%sample lengths.

clear, close all
NumOfStocks = 20;
randn('state',0);
SampleTests=[20,60,100,300,800];


%[CovBlocks, Combinations, SampleSizes, Sigma, StockReturns]=GetCovBlocks(0);
figure(1)
load data_10_blocks.mat

%Create 10 Sampled sequence of numbers. Maximum sample number = 10000.
Samples=randn(NumOfStocks,10000,10);
for i=1:10
    Samples(:,:,i)=Sigma^0.5*Samples(:,:,i);
end
error=[];

for iterBlocks=1:5
NumOfBlocks=2*iterBlocks;

%Define the covariance blocks for this iteration instance
CovBlocksIter=CovBlocks(1:NumOfBlocks);
CombinationsIter=Combinations(1:NumOfBlocks);


%Run the iterations for different sample lengths
for iterSamples=1:5
%Define number of samples per block
SampleLengths=SampleTests(iterSamples)*ones(1,NumOfBlocks);

%Define weights according to sample length, make them sum 1.
w=zeros(1,NumOfBlocks);
for i=1:NumOfBlocks
    w(1,i)=SampleLengths(1,i)/sum(SampleLengths);
end

for j=1:10
    for k=1:NumOfBlocks
        CovBlocksSampled{k,j}=cov(Samples(CombinationsIter{1,k},1:SampleLengths(1,k),j)');
    end
end

    cvx_begin
        cvx_quiet(true); 
        variable Sigma_hat(NumOfStocks, NumOfStocks) symmetric;
    
        %Define objective function
        f = 0;
        for a=1:10
            for q=1:NumOfBlocks
                f = f + w(1,q)*norm(Sigma_hat(CombinationsIter{q}, CombinationsIter{q})-CovBlocksSampled{q,a},'fro');           
            end
        end
        minimize (f)
    
        subject to
        
        Sigma_hat == semidefinite(NumOfStocks)
     cvx_end
    
%Now test the result using frobenius norm

error(iterSamples,iterBlocks)=norm(Sigma-Sigma_hat,'fro');
iterSamples
end

% subplot(2,3,iterBlocks)
% plot(1000*[1:iterSamples],error)
% title(['Error in estimation using Frobenius norm with ',num2str(NumOfBlocks), ' sub blocks'])
% xlabel('Number of samples for submatrices')
% ylabel('Error in frobenius norm')

end

figure(1)
    hold on
    plot(fliplr(error(:,2)'),'-g')
    plot(fliplr(error(:,3)'),'-b')
    plot(fliplr(error(:,4)'),'-r')
    plot(fliplr(error(:,5)'),'-y')
legend('4 Blocks', '6 Blocks', '8 Blocks', '10 Blocks') 
title('Error in estimation')
xlabel('Number of samples for submatrices')
ylabel('Error in frobenius norm')